<script setup lang="ts">
import { createSimulDataApi, getSimulInfoApi, updateSimulDataApi } from "@/api/resources/simul"
import { SimulBaseInfo } from "@/api/resources/simul/types/simul"
import { FormTypeEnum } from "@/constants/other-keys"
import { ElMessage, FormInstance, FormRules, genFileId, UploadProps, UploadRawFile, UploadUserFile } from "element-plus"
import { cloneDeep } from "lodash-es"
import { computed, ref, watch } from "vue"

interface Props {
  id: string | undefined
  dialogType: FormTypeEnum
  visible: boolean
}

const props = defineProps<Props>()
const emit = defineEmits(["closeDialog"])
const dialogVisible = ref<boolean>(false)
const DEFAULT_FORM_DATA: SimulBaseInfo = {
  sim_config_id: undefined,
  sim_config_name: "",
  sim_config_files_path: "",
  sim_config_describe: ""
}
const formRef = ref<FormInstance | null>(null)
const formData = ref<SimulBaseInfo>(cloneDeep(DEFAULT_FORM_DATA))
const formRules: FormRules<SimulBaseInfo> = {
  sim_config_name: [{ required: true, trigger: "blur", message: "请输入仿真资源名称" }]
}
const fileList = ref<UploadUserFile[]>([])
const loading = ref<boolean>(false)
const UploadFileRef = ref()

const textMap = computed(() => {
  if (props.dialogType == FormTypeEnum.CREATE) return "上传仿真资源"
  else if (props.dialogType == FormTypeEnum.EDIT) return "编辑仿真资源"
  else return "查看仿真资源"
})
const getSimulInfo = () => {
  props.id &&
    getSimulInfoApi(props.id).then(({ data }) => {
      if (data) {
        formData.value = cloneDeep(data)
      } else {
        ElMessage("数据不存在")
      }
    })
}
const showDialog = () => {
  formRef.value?.resetFields()
  fileList.value = []
  if (props.dialogType != FormTypeEnum.CREATE) {
    getSimulInfo()
  }
}
const closeDialog = () => {
  formRef.value?.resetFields()
  emit("closeDialog", undefined)
}
const handleFileChange: UploadProps["onChange"] = (uploadFile) => {
  fileList.value = [uploadFile]
}
const handleFileExceed: UploadProps["onExceed"] = (files) => {
  UploadFileRef.value!.clearFiles()
  const file = files[0] as UploadRawFile
  file.uid = genFileId()
  UploadFileRef.value!.handleStart(file)
}

const getParam = () => {
  const params = new FormData()
  if (props.dialogType != FormTypeEnum.CREATE && props.id) {
    params.append("sim_config_id", props.id)
  }
  params.append("sim_config_name", formData.value.sim_config_name)
  params.append("describe", formData.value.sim_config_describe)
  fileList.value.length > 0 && params.append("sim_config_files", fileList.value[0].raw as Blob)
  return params
}

const handleConfirm = () => {
  formRef.value?.validate((valid: boolean, fields) => {
    if (!valid) return console.error("表单校验不通过", fields)
    loading.value = true
    const api = props.dialogType == FormTypeEnum.CREATE ? createSimulDataApi : updateSimulDataApi
    const params: FormData = getParam()
    api(params)
      .then(() => {
        ElMessage.success("操作成功")
        emit("closeDialog", "refresh")
      })
      .finally(() => {
        loading.value = false
      })
  })
}

watch(
  () => [props.id, props.dialogType, props.visible],
  () => {
    dialogVisible.value = props.visible
    if (props.visible) {
      showDialog()
    }
  }
)

watch(
  () => fileList.value,
  () => {
    if (fileList.value.length > 0) {
      formData.value.sim_config_files_path = fileList.value[0].name
    }
  }
)
</script>
<template>
  <el-dialog :title="textMap" v-model="dialogVisible" width="600px" draggable @close="closeDialog">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="dialogType == FormTypeEnum.VIEW ? {} : formRules"
      width="700"
      label-width="140px"
      label-position="right"
      size="large"
      :close-on-click-modal="false"
      :disabled="dialogType == FormTypeEnum.VIEW"
    >
      <el-form-item label="仿真资源名称" prop="sim_config_name">
        <el-input v-model="formData.sim_config_name" autocomplete="off" placeholder="请输入" style="width: 240px" />
      </el-form-item>
      <el-form-item label="仿真资源文件" prop="sim_config_files_path">
        <el-upload
          v-if="dialogType != FormTypeEnum.VIEW"
          ref="UploadFileRef"
          v-model:file-list="fileList"
          :limit="1"
          :show-file-list="false"
          class="upload-demo"
          :auto-upload="false"
          :on-exceed="handleFileExceed"
          :on-change="handleFileChange"
        >
          <el-input v-model="formData.sim_config_files_path" placeholder="请选择">
            <template #append>
              <el-button>选择文件</el-button>
            </template>
          </el-input>
        </el-upload>
        <el-input v-else v-model="formData.sim_config_files_path" autocomplete="off" placeholder="请输入" />
      </el-form-item>
      <el-form-item label="仿真资源描述" prop="sim_config_describe">
        <el-input
          v-model="formData.sim_config_describe"
          :rows="3"
          type="textarea"
          :placeholder="`${props.dialogType == FormTypeEnum.VIEW ? '' : '可以输入仿真资源的基本逻辑，应用场景等信息，最多输入600字'}`"
          maxlength="600"
        />
      </el-form-item>
    </el-form>
    <template v-if="dialogType !== FormTypeEnum.VIEW" #footer>
      <div class="dialog-footer">
        <el-button @click="closeDialog">取 消</el-button>
        <el-button :loading="loading" type="primary" @click="handleConfirm">确 定</el-button>
      </div>
    </template>
    <template v-else #footer>
      <div class="dialog-footer">
        <el-button @click="closeDialog">关 闭</el-button>
      </div>
    </template>
  </el-dialog>
</template>
<style lang="scss" scoped>
.upload-demo {
  width: 100% !important;
}
:deep(.el-upload.el-upload--text) {
  width: 100% !important;
}
</style>
